package com.carrental.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.crm.dto.MarketingCampaignDTO;
import com.carrental.crm.entity.MarketingCampaign;
import com.carrental.crm.mapper.MarketingCampaignMapper;
import com.carrental.crm.service.MarketingCampaignService;
import com.carrental.crm.vo.MarketingCampaignVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 营销活动服务实现类
 */
@Service
public class MarketingCampaignServiceImpl extends ServiceImpl<MarketingCampaignMapper, MarketingCampaign> implements MarketingCampaignService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createMarketingCampaign(MarketingCampaignDTO marketingCampaignDTO) {
        // 创建营销活动实体
        MarketingCampaign marketingCampaign = new MarketingCampaign();
        BeanUtils.copyProperties(marketingCampaignDTO, marketingCampaign);
        
        // 设置默认值
        if (marketingCampaign.getStatus() == null) {
            // 根据开始时间设置状态
            LocalDateTime now = LocalDateTime.now();
            if (marketingCampaign.getStartTime().isAfter(now)) {
                marketingCampaign.setStatus(1); // 未开始
            } else if (marketingCampaign.getEndTime().isBefore(now)) {
                marketingCampaign.setStatus(3); // 已结束
            } else {
                marketingCampaign.setStatus(2); // 进行中
            }
        }
        
        if (marketingCampaign.getParticipantCount() == null) {
            marketingCampaign.setParticipantCount(0); // 参与人数初始为0
        }
        
        marketingCampaign.setCreateTime(LocalDateTime.now());
        marketingCampaign.setUpdateTime(LocalDateTime.now());
        
        // 保存营销活动信息
        save(marketingCampaign);
        return marketingCampaign.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMarketingCampaign(MarketingCampaignDTO marketingCampaignDTO) {
        if (marketingCampaignDTO.getId() == null) {
            throw new BusinessException("活动ID不能为空");
        }
        
        MarketingCampaign marketingCampaign = getById(marketingCampaignDTO.getId());
        if (marketingCampaign == null) {
            throw new BusinessException("活动不存在");
        }
        
        // 已结束或已取消的活动不能修改
        if (marketingCampaign.getStatus() == 3 || marketingCampaign.getStatus() == 4) {
            throw new BusinessException("已结束或已取消的活动不能修改");
        }
        
        BeanUtils.copyProperties(marketingCampaignDTO, marketingCampaign);
        
        // 根据开始时间和结束时间更新状态
        LocalDateTime now = LocalDateTime.now();
        if (marketingCampaign.getStartTime().isAfter(now)) {
            marketingCampaign.setStatus(1); // 未开始
        } else if (marketingCampaign.getEndTime().isBefore(now)) {
            marketingCampaign.setStatus(3); // 已结束
        } else {
            marketingCampaign.setStatus(2); // 进行中
        }
        
        marketingCampaign.setUpdateTime(LocalDateTime.now());
        
        return updateById(marketingCampaign);
    }

    @Override
    public MarketingCampaignVO getMarketingCampaignById(Long id) {
        MarketingCampaign marketingCampaign = getById(id);
        if (marketingCampaign == null) {
            return null;
        }
        return convertToVO(marketingCampaign);
    }

    @Override
    public Page<MarketingCampaignVO> pageMarketingCampaigns(Page<MarketingCampaign> page, String name, Integer type, Integer status, String startTime, String endTime) {
        LambdaQueryWrapper<MarketingCampaign> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(MarketingCampaign::getName, name);
        }
        if (type != null) {
            queryWrapper.eq(MarketingCampaign::getType, type);
        }
        if (status != null) {
            queryWrapper.eq(MarketingCampaign::getStatus, status);
        }
        
        // 处理时间范围
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(startTime)) {
            LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
            queryWrapper.ge(MarketingCampaign::getCreateTime, startDateTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
            queryWrapper.le(MarketingCampaign::getCreateTime, endDateTime);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(MarketingCampaign::getCreateTime);
        
        // 执行分页查询
        Page<MarketingCampaign> marketingCampaignPage = page(page, queryWrapper);
        return convertToVOPage(marketingCampaignPage);
    }

    @Override
    public Page<MarketingCampaignVO> getOngoingMarketingCampaigns(Page<MarketingCampaign> page) {
        LocalDateTime now = LocalDateTime.now();
        
        LambdaQueryWrapper<MarketingCampaign> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(MarketingCampaign::getStartTime, now)
                .ge(MarketingCampaign::getEndTime, now)
                .eq(MarketingCampaign::getStatus, 2) // 进行中
                .orderByDesc(MarketingCampaign::getCreateTime);
        
        Page<MarketingCampaign> marketingCampaignPage = page(page, queryWrapper);
        return convertToVOPage(marketingCampaignPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMarketingCampaignStatus(Long id, Integer status) {
        if (id == null || status == null) {
            throw new BusinessException("参数不能为空");
        }
        
        MarketingCampaign marketingCampaign = getById(id);
        if (marketingCampaign == null) {
            throw new BusinessException("活动不存在");
        }
        
        // 已结束的活动不能改为其他状态
        if (marketingCampaign.getStatus() == 3 && status != 3) {
            throw new BusinessException("已结束的活动不能改为其他状态");
        }
        
        marketingCampaign.setStatus(status);
        marketingCampaign.setUpdateTime(LocalDateTime.now());
        
        return updateById(marketingCampaign);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementParticipantCount(Long id) {
        if (id == null) {
            throw new BusinessException("活动ID不能为空");
        }
        
        MarketingCampaign marketingCampaign = getById(id);
        if (marketingCampaign == null) {
            throw new BusinessException("活动不存在");
        }
        
        // 只有进行中的活动可以增加参与人数
        if (marketingCampaign.getStatus() != 2) {
            throw new BusinessException("只有进行中的活动可以增加参与人数");
        }
        
        // 使用更新条件包装器直接更新数据库中的参与人数
        LambdaUpdateWrapper<MarketingCampaign> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MarketingCampaign::getId, id)
                .setSql("participant_count = participant_count + 1")
                .set(MarketingCampaign::getUpdateTime, LocalDateTime.now());
        
        return update(updateWrapper);
    }

    /**
     * 将营销活动实体转换为VO
     *
     * @param marketingCampaign 营销活动实体
     * @return 营销活动VO
     */
    private MarketingCampaignVO convertToVO(MarketingCampaign marketingCampaign) {
        if (marketingCampaign == null) {
            return null;
        }
        
        MarketingCampaignVO vo = new MarketingCampaignVO();
        BeanUtils.copyProperties(marketingCampaign, vo);
        
        // 设置类型名称
        if (marketingCampaign.getType() != null) {
            switch (marketingCampaign.getType()) {
                case 1:
                    vo.setTypeName("满减");
                    break;
                case 2:
                    vo.setTypeName("折扣");
                    break;
                case 3:
                    vo.setTypeName("优惠券");
                    break;
                case 4:
                    vo.setTypeName("赠品");
                    break;
                default:
                    vo.setTypeName("未知");
            }
        }
        
        // 设置状态名称
        if (marketingCampaign.getStatus() != null) {
            switch (marketingCampaign.getStatus()) {
                case 1:
                    vo.setStatusName("未开始");
                    break;
                case 2:
                    vo.setStatusName("进行中");
                    break;
                case 3:
                    vo.setStatusName("已结束");
                    break;
                case 4:
                    vo.setStatusName("已取消");
                    break;
                default:
                    vo.setStatusName("未知");
            }
        }
        
        // 处理适用车型和门店名称（实际项目中可能需要调用其他服务获取名称）
        // 这里简单处理，实际项目中可能需要调用车辆服务和门店服务获取名称
        if (StringUtils.isNotBlank(marketingCampaign.getApplicableVehicles())) {
            vo.setApplicableVehicleNames("适用车型" + marketingCampaign.getApplicableVehicles());
        }
        
        if (StringUtils.isNotBlank(marketingCampaign.getApplicableStores())) {
            vo.setApplicableStoreNames("适用门店" + marketingCampaign.getApplicableStores());
        }
        
        return vo;
    }

    /**
     * 将营销活动分页数据转换为VO分页
     *
     * @param page 营销活动分页
     * @return 营销活动VO分页
     */
    private Page<MarketingCampaignVO> convertToVOPage(Page<MarketingCampaign> page) {
        Page<MarketingCampaignVO> voPage = new Page<>();
        BeanUtils.copyProperties(page, voPage, "records");
        
        List<MarketingCampaignVO> voList = new ArrayList<>();
        for (MarketingCampaign marketingCampaign : page.getRecords()) {
            voList.add(convertToVO(marketingCampaign));
        }
        voPage.setRecords(voList);
        
        return voPage;
    }
} 